package com.atdel.demo07;


import org.junit.Test;

import java.util.Random;
import java.util.concurrent.*;

/**
 * @BelongsProject: java_study
 * @BelongsPackage: com.atdel.demo07
 * @Author: Del
 * @CreateTime: 2025-03-07  10:09
 * @Description:
 * @Version: 1.0
 */
public class ThreadTest {

    /**
     * 使用线程池执行多个任务
     */
    @Test
    public void test01() {
        // 创建线程池
        ExecutorService executor = Executors.newFixedThreadPool(3);

        // 创建三个Callable任务
        Callable<Integer> redTask = () -> new Random().nextInt(256);
        Callable<Integer> greenTask = () -> new Random().nextInt(256);
        Callable<Integer> blueTask = () -> new Random().nextInt(256);

        // 提交任务并获取Future对象
        Future<Integer> redFuture = executor.submit(redTask);
        Future<Integer> greenFuture = executor.submit(greenTask);
        Future<Integer> blueFuture = executor.submit(blueTask);

        try {
            // 获取结果
            int redValue = redFuture.get();
            int greenValue = greenFuture.get();
            int blueValue = blueFuture.get();

            System.out.println("红色值: " + redValue);
            System.out.println("绿色值: " + greenValue);
            System.out.println("蓝色值: " + blueValue);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } finally {
            executor.shutdown();
        }
    }

    @Test
    public void test02() {

        // 创建一个单线程线程池
        ExecutorService executor = Executors.newSingleThreadExecutor();

        // 创建一个Callable任务
        Callable<String> RGB = () -> {
            // 生成随机数
            int red = new Random().nextInt(256);
            int green = new Random().nextInt(256);
            int blue = new Random().nextInt(256);
            return "RGB: " + "[" + red + "," + green + "," + blue + "]";
        };

        // 提交任务并获取Future对象
        Future<String> future = executor.submit(RGB);

        try {
            // 获取结果
            String color = future.get();
            System.out.println(color);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } finally {
            // 关闭线程池
            executor.shutdown();
        }
    }
}